package com.itheima.mm.controller;

import com.alibaba.fastjson.JSON;
import com.itheima.framework.annotation.HmComponent;
import com.itheima.framework.annotation.HmRequestMapping;
import com.itheima.framework.annotation.HmSetter;
import com.itheima.mm.base.BaseController;
import com.itheima.mm.common.GlobalConst;
import com.itheima.mm.entity.Result;
import com.itheima.mm.pojo.User;
import com.itheima.mm.service.UserService;
import com.itheima.mm.service.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.rmi.ServerException;

/**
 * @author ：wanghao
 * @date ：Created in 2020/10/18
 * @description ：
 * @version: 1.0
 */
@HmComponent
@Slf4j
public class UserController extends BaseController {

    @HmSetter("userService")
    private UserService userService;

    /**
     * 用户登录
     * @param request
     * @param response
     * @throws IOException
     * @throws ServerException
     */
    @HmRequestMapping("/user/login")
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServerException {
        // 1. 接收前端数据(json格式),封装到pojo对象
        User userForm = JSON.parseObject(request.getInputStream(), User.class);
        log.debug("页面数据：userForm{}"+userForm);
        // 调用service完成登录
        User userDao = userService.findUserByUsername(userForm.getUsername());
        // 判断用户是否为null
        if (userDao == null){
            // 响应JSON
            Result result = new Result(false,"登录失败，用户名不存在！！！");
            printResult(response,request);
            return;
        }
        // 用户存在，判断密码是否一致
        if (userDao.getPassword().equals(userForm.getPassword())){
            // 创建session对象
            HttpSession session = request.getSession(true);
            // 登录成功，把用户信息存入session
            session.setAttribute(GlobalConst.SESSION_KEY_USER,userDao);
            printResult(response,new Result(true,"登录成功",userDao.getUsername()));
        }else {
            printResult(response,new Result(false,"登录失败，密码错误！！！"));
        }
    }

    /**
     * 用户退出登录
     * @param request
     * @param response
     * @throws IOException
     * @throws ServerException
     */
    @HmRequestMapping("/user/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException, ServerException {
        // 销毁会话，如果没有session，无需再创建
        HttpSession session = request.getSession(false);
        if (session != null){
            // 销毁session
            log.debug("销毁session...");
            session.invalidate();
        }else {
            log.debug("session已失效...");
        }
        // 响应json到客户端
        printResult(response,new Result(true,"退出登陆成功"));
    }
}
